package com.lxd.sunso.product.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxd.sunso.common.utils.PageUtils;
import com.lxd.sunso.common.utils.Query;
import com.lxd.sunso.product.components.BCryptPasswordEncoderUtil;
import com.lxd.sunso.product.entity.CustomerEntity;
import com.lxd.sunso.product.entity.RoleUserEntity;
import com.lxd.sunso.product.service.CustomerService;
import com.lxd.sunso.product.service.RoleUserService;
import com.lxd.sunso.product.vo.UserDetailVo;
import com.lxd.sunso.product.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxd.sunso.product.dao.UserDao;
import com.lxd.sunso.product.entity.UserEntity;
import com.lxd.sunso.product.service.UserService;
import org.springframework.util.StringUtils;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Autowired
    BCryptPasswordEncoderUtil bCryptPasswordEncoderUtil;

    @Autowired
    CustomerService customerService;

    @Autowired
    RoleUserService roleUserService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //获取当前用户的权限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> authorities =
                authentication.getAuthorities();

        if (!authorities.toString().equals("[ROLE_ADMIN]")) {
            IPage<UserEntity> page = this.page(
                    new Query<UserEntity>().getPage(params),
                    new QueryWrapper<UserEntity>().ne("userName", "admin")
            );
            PageUtils pageUtils = new PageUtils(page);
            List<UserEntity> collect = page.getRecords();
            List<UserDetailVo> collect1 = collect.stream().map(userEntity -> {
                String customerId = userEntity.getUserid();
                CustomerEntity customerEntity = customerService.getById(customerId);
                userEntity.setUserid(customerEntity.getCustomername());
                UserDetailVo userDetailVo = new UserDetailVo();
                BeanUtils.copyProperties(userEntity, userDetailVo);
                return userDetailVo;
            }).collect(Collectors.toList());
            pageUtils.setList(collect1);
            return pageUtils;
        } else {
            IPage<UserEntity> page = this.page(
                    new Query<UserEntity>().getPage(params),
                    new QueryWrapper<UserEntity>()
            );
            PageUtils pageUtils = new PageUtils(page);
            List<UserEntity> collect = page.getRecords();
            List<UserDetailVo> collect1 = collect.stream().map(userEntity -> {
                String customerId = userEntity.getUserid();
                CustomerEntity customerEntity = customerService.getById(customerId);
                userEntity.setUserid(customerEntity.getCustomername());
                UserDetailVo userDetailVo = new UserDetailVo();
                BeanUtils.copyProperties(userEntity, userDetailVo);
                return userDetailVo;
            }).collect(Collectors.toList());
            pageUtils.setList(collect1);
            return pageUtils;
        }
    }

    @Override
    public PageUtils search(Map<String, Object> params) {
        //获取当前用户的权限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> authorities =
                authentication.getAuthorities();

        IPage<UserEntity> page = null;
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        String userName = (String) params.get("UserName");
        String fullName = (String) params.get("FullName");
        String status = (String) params.get("Status");

        if (!StringUtils.isEmpty(userName)) {
            queryWrapper.like("UserName", userName);
        }
        if (!StringUtils.isEmpty(fullName)) {
            queryWrapper.like("FullName", fullName);
        }
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("Status", status);
        }

        if (!authorities.toString().equals("[ROLE_ADMIN]")) {
            queryWrapper.ne("UserName", "admin");
        }

        page = this.page(new Query
                <UserEntity>().getPage(params), queryWrapper);
        List<UserEntity> userEntities = page.getRecords();
        List<UserEntity> collect = userEntities.stream().map(userEntity -> {
            String customerId = userEntity.getUserid();
            CustomerEntity customerEntity = customerService.getById(customerId);
            userEntity.setUserid(customerEntity.getCustomername());
            return userEntity;
        }).collect(Collectors.toList());
        return new PageUtils(page.setRecords(collect));
    }

    @Override
    public UserEntity findById(Long id) {
        UserEntity userEntity = this.getById(id);
        final CustomerEntity customerEntity = customerService.getById(userEntity.getUserid());
        userEntity.setUserid(customerEntity.getCustomername());
        return userEntity;
    }

    @Override
    public void newUpdate(UserEntity user) {
        String customerName = user.getUserid();
        String password = user.getPassword();
        if (password.equals("******")) {
            UserEntity userEntity = this.getById(user.getId());
            user.setPassword(userEntity.getPassword());
        } else {
            String encode = bCryptPasswordEncoderUtil.encode(password);
            user.setPassword(encode);
        }
        CustomerEntity customerEntity = customerService.getOne(new QueryWrapper<CustomerEntity>().eq("CustomerName", customerName));
        if (customerEntity == null) {
            this.updateById(user);
        } else {
            user.setUserid(customerEntity.getId().toString());
            this.updateById(user);
        }
    }


    /**
     * 个性化验证登录
     *
     * @param username    账号
     * @param rawPassword 原始密码
     * @return
     */
    @Override
    public boolean checkLogin(final String username, final String rawPassword) throws Exception {
        UserEntity userEntity = this.getUserByUserName(username);
        if (userEntity == null) {
            // System.out.println("checkLogin--------->账号不存在，请重新尝试！");
            // 设置友好提示
            throw new Exception("账号不存在，请重新尝试！");
        } else {
            // 加密的密码
            final String encodedPassword = userEntity.getPassword();
            // 和加密后的密码进行比配
            if (!bCryptPasswordEncoderUtil.matches(rawPassword, encodedPassword)) {
                throw new Exception("密码不正确，请重试");
            } else if (!userEntity.getStatus().equals("0")) {
                switch (userEntity.getStatus()) {
                    case "1":
                        throw new Exception("账号已停用，请联系管理员");
                    case "2":
                        throw new Exception("账号已锁定，请联系管理员");
                    case "3":
                        throw new Exception("账号无效，请联系管理员");
                }
            }
            return true;
        }
    }

    @Override
    public UserEntity getUserByUserName(String username) {
        UserEntity userEntity = this.getOne(new QueryWrapper<UserEntity>().eq("UserName", username));
        return userEntity;
    }

    /**
     * 新增用户以及对应的权限
     *
     * @param user
     * @return
     */
    @Override
    public boolean saveUser(UserEntity user) {
        UserEntity userEntity = this.getOne(new QueryWrapper<UserEntity>().eq("UserName", user.getUsername()));
        if (userEntity != null) {
            return false;
        } else {
            RoleUserEntity roleUserEntity = new RoleUserEntity();
            this.save(user);
            roleUserEntity.setRoleid(user.getRoleids());
            roleUserEntity.setUserid(user.getId().toString());
            roleUserService.save(roleUserEntity);
            return true;
        }
    }

    /**
     * 根据用户名称得到顾客名称
     *
     * @param username
     * @return
     */
    @Override
    public String findCustomerByUser(String username) {
        UserEntity userEntity = this.getOne(new QueryWrapper<UserEntity>().eq("UserName", username));
        CustomerEntity customerEntity = customerService.getById(userEntity.getUserid());
        return customerEntity.getCustomername();
    }

    /**
     * 修改密码操作
     *
     * @param userVo
     * @return
     */
    @Override
    public boolean changePassword(UserVo userVo) {
        String userName = userVo.getUserName();
        String oldPassword = userVo.getOldPassword();
        String newPassword = userVo.getNewPassword();
        UserEntity entity = this.getOne(new QueryWrapper<UserEntity>().eq("UserName", userName));
        String encodedPassword = entity.getPassword();
        if (!bCryptPasswordEncoderUtil.matches(oldPassword, encodedPassword)) {
            return false;
        } else {
            String encode = bCryptPasswordEncoderUtil.encode(newPassword);
            entity.setPassword(encode);
            this.updateById(entity);
            return true;
        }
    }

    /**
     * 获取管理员的姓名
     *
     * @param roleId
     * @return
     */
    @Override
    public List<String> getAdminName(String roleId) {
        List<String> adminName = this.baseMapper.getAdminName(roleId);
        return adminName;
    }
}